<template>
	<view class="page">
		
		<view class="layout">
			
			<view v-for="(item,index) in dataList" :key="item._id" class="box">
				
				<view class="pic" @click="onPreview(index)">
					<image :src="item.url" lazy-load mode="widthFix"></image>
				</view>
				
				<view class="text">
					<text>{{item.content}}</text>
				</view>
				
			</view>
			
			<view v-show="isLoading" class="isLoading">
				加载中...
			</view>
			
			<view v-show="!isHasMore && !isLoading" class="isHasMore">
				没有更多数据了...
			</view>
			
		</view>
		
	</view>
</template>


<script setup>
	import {
		ref
	} from "vue";
	import {
		onLoad,
		onPullDownRefresh,
		onReachBottom,
	} from "@dcloudio/uni-app";

	// 
	onLoad(() => {
		getData();
	});

	// 
	onPullDownRefresh(() => {
		console.log("~~~下拉刷新");
		dataList.value = [];
		page.value = 1;
		isHasMore.value = true;
		getData();
	});

	// 
	onReachBottom(() => {
		if (isHasMore.value) {
			console.log("~~~上拉加载");
			getData();
		}
	});

	// 
	const dataList = ref([]);
	const page = ref(1);
	const isLoading = ref(true);
	const isHasMore = ref(true);
	const getData = () => {
		console.log("~~~获取数据");
		isLoading.value = true;
		uni.showNavigationBarLoading();
		uni.showLoading({
			title: "加载中..."
		});

		uni.request({
			url: `https://tea.qingnian8.com/tools/petShow`,
			data: {
				size: 5
			},
			method: "GET",
			header: {
				'access-key': "020313key"
			},

			success: res => {
				console.log(`~~~ page = ${page.value}`);

				let newList = [...dataList.value];
				if (page.value === 1) newList = [];
				dataList.value = newList.concat(res.data.data || []);
				isLoading.value = false;
				isHasMore.value = res.data.data && res.data.data.length >= 5;
				page.value++;
				console.log("~~~", dataList.value);

				uni.hideLoading();
				uni.showToast({
					title: "加载成功",
					icon: "success"
				});
			},

			fail: res => {
				console.log("~~~", res.data);
				uni.hideLoading();
				uni.showToast({
					title: "加载失败",
					icon: 'error'
				});
			},

			complete: () => {
				uni.hideNavigationBarLoading();
				uni.stopPullDownRefresh();
			}
		})
	};

	// 
	const onPreview = (index) => {
		console.log(`~~~从第 ${index+1} 张图片开始预览`);
		let urlList = dataList.value.map(item => item.url);
		uni.previewImage({
			current: index,
			urls: urlList,
			showmenu: true
		})
	};
</script>


<style lang="scss" scoped>
	@use 'index.scss';
</style>